package com.xoa.controller.nccloud;

import com.alibaba.fastjson.JSON;
import com.xoa.dao.WFE.WFEFlowProcessMapper;
import com.xoa.dao.WFE.WFEFlowTypeModelMapper;
import com.xoa.dao.WFE.WFEFormTypeMapper;
import com.xoa.dao.flowRunFeedback.FlowRunFeedbackMapper;
import com.xoa.dao.flowhook.FlowHookMapper;
import com.xoa.dao.flowplugin.FlowPluginMapper;
import com.xoa.dao.sms.SmsBodyMapper;
import com.xoa.dao.sms.SmsMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowProcessMapper;
import com.xoa.dao.workflow.FlowRunAttachMapper;
import com.xoa.dao.workflow.FlowSortMapper;
import com.xoa.dao.workflow.FlowTiggerMapper;
import com.xoa.dev.workFlow.controller.WorkFlowCreateController;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFormType;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.plugin.*;
import com.xoa.plugin.ct.*;
import com.xoa.plugin.jf.JFPsnInnerStapplyPushTrigger;
import com.xoa.plugin.jf.JFPsnLeavePushTrigger;
import com.xoa.plugin.jf.JFWorkApi;
import com.xoa.plugin.sej.SEJPsnLeavePushTrigger;
import com.xoa.plugin.sej.SEJWorkApi;
import com.xoa.service.WFE.WFEFactory.WFEFlowProcess;
import com.xoa.service.WFE.WFEFactory.WFEFlowType;
import com.xoa.service.WFE.WFEFactory.WFEFormType;
import com.xoa.service.WFE.WFERunner.WFEFlowRun;
import com.xoa.service.WFE.WFERunner.WFEFlowRunPrcs;
import com.xoa.service.work.WorkService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表单提交前向nc推送数据处理
 */
@RestController
@RequestMapping(value = "/WorkFlowBeginTrigger/api")
public class WorkFlowBeginController {

    @Autowired
    protected WFEFlowProcessMapper wfeFlowProcessMapper;

    @Autowired
    protected WFEFlowType wfeFlowType;

    @Autowired
    protected WFEFormType wfeFormType;

    @Autowired
    protected WFEFlowProcess wfeFlowProcess;

    @Autowired
    protected WFEFlowRun wfeFlowRun;

    @Autowired
    protected WFEFlowRunPrcs wfeFlowRunPrcs;

    @Autowired
    protected WFEFlowTypeModelMapper wfeFlowTypeModelMapper;

    @Autowired
    protected WFEFormTypeMapper wfeFormTypeMapper;

    @Autowired
    protected WorkMapper workMapper;

    @Autowired
    protected FlowProcessMapper flowProcessMapper;


    @Autowired
    protected FlowTiggerMapper flowTiggerMapper;

    @Autowired
    protected FlowPluginMapper flowPluginMapper;

    @Autowired
    protected FlowHookMapper flowHookMapper;

    @Autowired
    protected FlowRunFeedbackMapper flowRunFeedbackMapper;

    @Autowired
    protected WorkService workService;


    @Autowired
    protected FlowSortMapper flowSortMapper;

    @Autowired
    protected SmsMapper smsMapper;

    @Autowired
    protected SmsBodyMapper smsBodyMapper;

    @Autowired
    protected FlowRunAttachMapper flowRunAttachMapper;

    @Autowired
    WorkFlowCreateController workFlowCreateController;
    @Autowired
    CTPsnLeavePushTrigger psnLeavePushTrigger;
    @Autowired
    CTWorkApi workApi;
    @Autowired
    PsnStapplyPushTrigger psnStapplyPushTrigger;
    @Autowired
    CTPsnInnerStapplyPushTrigger psnInnerStapplyPushTrigger;
    @Autowired
    JFPsnLeavePushTrigger jfPsnLeavePushTrigger;
    @Autowired
    JFPsnInnerStapplyPushTrigger jfPsnInnerStapplyPushTrigger;
    @Autowired
    JFWorkApi jfWorkApi;
    @Autowired
    CTHRPsnLeavePushTrigger cthrPsnLeavePushTrigger;
    @Autowired
    CTHRWorkApi cthrWorkApi;
    @Autowired
    SEJPsnLeavePushTrigger sejPsnLeavePushTrigger;
    @Autowired
    SEJWorkApi sejWorkApi;

    /**
     * 内置
     */
    private final int BUILT_IN = 0;
    /**
     * 对外接口获取数据
     */
    private final int BUILT_OUT = 1;
    /**
     * 数据推送对方接口
     */
    private final int BUILT_PUSH = 2;

    /**
     * 新建操作
     */
    private static int create = 1;

    /**
     * 接收操作
     */
    private static int receive = 2;

    /**
     * 保存操作
     */
    private static int save = 3;

    /**
     * 转交操作
     */
    private static int turn = 4;

    /**
     * 委托操作
     */
    private static int intrust = 5;

    /**
     * 退回操作
     */
    private static int back = 6;

    @RequestMapping(value = "/beginSubmit",method = RequestMethod.POST)
    public ToJson beginSubmit(
            HttpServletRequest httpServletRequest,
            @RequestParam(value = "runId") Integer runId,
            @RequestParam(value = "runName") String runName,
            @RequestParam(value = "flowId") Integer flowId,
            @RequestParam(value = "prcsId") Integer prcsId,
            @RequestParam(value = "prcsflag", required = false) String prcsFlag,
            @RequestParam(value = "flowPrcs") String flowPrcs,
            @RequestParam(value = "beginTime") String beginTime,
            @RequestParam(value = "beginUser") String beginUser,
            @RequestParam(value = "jingbanUser", required = false) String jingbanUser,
            @RequestParam(value = "currentPrcsId") Integer currentPrcsId,
            @RequestParam(value = "orgAdd", required = false) String orgadd,
            @RequestParam(value = "viewUser", required = false) String viewUser,
            @RequestParam(value = "smsContent", required = false) String smsContent,
            @RequestParam(value = "smsType", required = false) String smsType,
            @RequestParam(value = "tableName", required = false) String tableName,
            @RequestParam(value = "tabId") String tabId,
            @RequestParam(value = "flowStep", required = false) String flowStep,
            @RequestParam(value = "htmlContent", required = false) String htmlContent
    )throws Exception{
        //表单参数提取处公共方类
        TriggerPlugIn triggerPlugIn = null;
        //返回对象信息
        ToJson toJson=new ToJson();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            if (StringUtils.checkNull((String) request.getSession().getAttribute(
                    "loginDateSouse"))) {
                sqlType = "xoa1001";
            }

            //=================================城投
            //个人离职
            if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==255){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=psnLeavePushTrigger.doRun(triggerPlugIn);
                //个人转正
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==232){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=workApi.doRun(triggerPlugIn);

                //人事发起转正
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==311){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=cthrWorkApi.doRun(triggerPlugIn);

                //人事审批离职
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==303){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=cthrPsnLeavePushTrigger.doRun(triggerPlugIn);

                //内部调动
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==292){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=psnInnerStapplyPushTrigger.doRun(triggerPlugIn);

                //=================================建发
                //离职
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==308){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=jfPsnLeavePushTrigger.doRun(triggerPlugIn);
                //转正
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==313){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=jfWorkApi.doRun(triggerPlugIn);
                //内部调动
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==310) {
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson = jfPsnInnerStapplyPushTrigger.doRun(triggerPlugIn);
                //=================================省二建
                //离职
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==314){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=sejPsnLeavePushTrigger.doRun(triggerPlugIn);
                //转正
            }else if(org.apache.commons.lang3.StringUtils.isNotBlank(flowId.toString()) && flowId==313){
                triggerPlugIn = this.getTrigger(runId.toString(), flowId.toString(), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
                toJson=sejWorkApi.doRun(triggerPlugIn);
                //内部调动
            }else {
                toJson.setFlag(0);
            }

        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());

        }
        return toJson;
    }


    public TriggerPlugIn getTrigger(String runId, String flowId, String sqlType, String beginUser, String beginTime, String runName, String flowPrcs, String prcsId, String currentPrcsId,
                                    String tabId, HttpServletRequest request, int turn) {
        //此map用来传递参数
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", "flow_data_" + flowId);
        param.put("runId", runId);
        //查询存储存入数据库中信息
        Map<String, Object> flowDatas = workMapper.select(param);
        //此处代码可修改流程触发器解析表单的代码直接传入map省去此步骤
        String flowDataString = CollectionUtils.mapToString(flowDatas);

        if (StringUtils.checkNull(sqlType)) {
            param.put("tableSchema", "xoa1001");
        } else {
            param.put("tableSchema", sqlType);
        }
        //存储表单上映射
        Map<String, Object> mapForm = new HashMap<String, Object>();
        List<FlowFormType> allFlowForm = wfeFormTypeMapper.getFrombyFlowId(Integer.parseInt(flowId));
        FlowFormType flowFormType = allFlowForm.get(0);
        //获取表单信息
        Document document = HtmlUtil.getDom(flowFormType.getPrintModel());
        //获取该表所有的列
        List<String> columns = workMapper.showColumns(param);
        for (int i = 0, size = columns.size(); i < size; i++) {
            String name = HtmlUtil.getDocumentTitle(document, columns.get(i));
            String data = HtmlUtil.getDocumentName(document, name);
            mapForm.put(name, data);
        }
        //表单数据
        String fromString = JSON.toJSONString(mapForm);
        //插件类
        TriggerPlugIn triggerPlugIn = new TriggerPlugIn();
        triggerPlugIn.setFlowId(flowId);
        triggerPlugIn.setFormmat("2");//超链接格式//适用公告
        triggerPlugIn.setFromId(beginUser);
        triggerPlugIn.setSendTime(DateFormat.getDate(beginTime));
        triggerPlugIn.setSubject(runName);
        String url = request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/workflow/work/workformPreView?flowId=" + Integer.valueOf(flowId) + "&flowStep=" + Integer.valueOf(prcsId) + "&runId=" + runId + "";
        triggerPlugIn.setContent("<a href=" + url + ">" + url + "</a>");
        triggerPlugIn.setToId2("");
        triggerPlugIn.setFlowPrcs(flowPrcs);
        triggerPlugIn.setPrcsId(prcsId);
        triggerPlugIn.setModify(flowDataString);
        triggerPlugIn.setReject(fromString);
        triggerPlugIn.setTableName(runName);
        triggerPlugIn.setRunId(runId + "");
        triggerPlugIn.setRunName(runName);
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        triggerPlugIn.setUsers(user);
        triggerPlugIn.setFlag(this.returnMap().get(turn));
        triggerPlugIn.setRequest(request);
        triggerPlugIn.setSqlType(sqlType);
        triggerPlugIn.setTabId(tabId);
        triggerPlugIn.setCurrentPrcsId(currentPrcsId);
        return triggerPlugIn;
    }


    public Map<Integer, String> returnMap() {
        Map<Integer, String> maps = new HashMap<Integer, String>();
        maps.put(1, "CREATE");
        maps.put(2, "RECEIVE");
        maps.put(3, "SAVE");
        maps.put(4, "TURN");
        maps.put(5, "INTRUST");
        maps.put(6, "BACK");
        return maps;
    }
}
